import axios from "axios";

const fs = require('fs');
const path = require('path');


/**
 * 读取路径信息
 * @param {string} path 路径
 */
//@ts-ignore
function getStat(path) {
    return new Promise((resolve, reject) => {
        //@ts-ignore
        fs.stat(path, (err, stats) => {
            if (err) {
                resolve(false);
            } else {
                resolve(stats);
            }
        })
    })
}

/**
  * 创建路径
  * @param {string} dir 路径
  */
//@ts-ignore
function mkdir(dir) {
    return new Promise((resolve, reject) => {
        //@ts-ignore
        fs.mkdir(dir, err => {
            if (err) {
                resolve(false);
            } else {
                resolve(true);
            }
        })
    })
}

/**
  * 路径是否存在，不存在则创建
  * @param {string} dir 路径
  */
//@ts-ignore
export async function dirExists(dir) {
    let isExists = await getStat(dir);
    //如果该路径且不是文件，返回true
    //@ts-ignore
    if (isExists && isExists.isDirectory()) {
        return true;
    } else if (isExists) {
        //如果该路径存在但是文件，返回false
        return false;
    }
    //如果该路径不存在，拿到上级路径
    let tempDir = path.parse(dir).dir;
    //递归判断，如果上级目录也不存在，则会代码会在此处继续循环执行，直到目录存在
    let status = await dirExists(tempDir);
    let mkdirStatus;
    if (status) {
        mkdirStatus = await mkdir(dir);
    }
    return mkdirStatus;
}

/**
 * 写入文件
 * @param text 
 * @param path 
 */
export function writeTxtToPath(text: string, path: string) {
    return new Promise(async (reslove: Function) => {
        try {
            // Write the content to the file
            await fs.writeFileSync(path, text);
            reslove()
        } catch (err) {
            reslove({
                err:err
            })
        }
    })
}

/**
 * 拷贝文件到
 * @param path 
 * @param toPath 
 */
export function cpFile(path: string, toPath: string) {
    return new Promise((reslove: Function) => {
        try {
            //@ts-ignore
            fs.copyFile(path, toPath, (err) => {
                if (err) {
                    reslove({
                        err: err
                    })
                } else {
                    reslove({
                        err: null
                    })
                }
            });
        } catch (err) {
            reslove({
                err: err
            })
        }

    })
}

export function dwFileUrl(url: string, filePath: string) {
    return new Promise((reslove: Function) => {
        axios.get(url, { responseType: 'stream' })
            .then((response: any) => {
                // console.warn("下载成功")
                const writer = fs.createWriteStream(filePath);
                response.data.pipe(writer);
                reslove({})
            })
            .catch((error: any) => {
                reslove({
                    err: error
                })
            });
    })

}


const  savedTexture:{[key:string]:string} = {} 
/**
 * 保存图集到图集对应的文件
 * @param url 
 * @param filePath 
 */
export function saveImgToTextureAssets(url:string,filePath:string,isSave:boolean = true){
    return saveHandel(url,filePath,1000,isSave)
}

export function saveAudioFile(url:string,filePath:string){
    return saveHandel(url,filePath)
}
export function saveUrlToFile(
    url:string,
    filePath:string
){
    return saveHandel(url,filePath)
}
export function saveHandel(url:string,filePath:string,awaitTime:number   = 100,isSaveCatch:boolean = true){
    return new Promise(async (reslove: Function) => {
        if(savedTexture[`${url}_${filePath}`]){
            await cpFile(savedTexture[url],filePath)
            reslove({err:null})
            return
        }
        axios.get(url, { responseType: 'stream' })
            .then(async (response: any) => {
                // console.warn("下载成功")
                const writer = fs.createWriteStream(filePath);
                let task =  await response.data.pipe(writer);
                // console.warn(task.on)
                let stream =  response.data
                stream.on("end", () =>{
                    savedTexture[`${url}_${filePath}`] = filePath;
                    setTimeout(() => {
                        reslove({err:null})
                        //防止被反爬虫识别
                    }, awaitTime);
                });
            })
            .catch((error: any) => {
                reslove({
                    err: error
                })
            });
    })
}
export function readUrlJson(url:string){
    return new Promise((reslove:Function)=>{
        axios.get(url)
        .then((res)=>{
            reslove({
                err:null,
                data:res.data
            })
        })
    })
}

/**
 * 
 * @param url 
 */
export function readTextForUrl(url:string){
    return new Promise((reslove:Function)=>{
        axios.get(url)
        .then((res)=>{
            reslove({
                err:null,
                data:res.data
            })
        })
        .catch(()=>{
            reslove({
                err:new Error("没读取到"),
                data:null
            })
        })
    })
}